const { writeFileSync } = require('fs');
const http = require('http');

const server = http.createServer((req, res) =>{
    const url = req.url,
          method = req.method;
    if (url === '/form') {
        res.statusCode = 200;
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Content-Type', 'text/html;charset=utf8');
        res.write('<html><body>');
        res.write('<form action="/message" method="post"><input type="text" name="message" /><input type="submit" value="提交" /></form>');
        res.write('</body></html>');
        return res.end();
    } else if (url === '/message' && method == 'POST') {
        const list = [];
        req.on('data', chunk => {
            list.push(chunk);
        })
        req.on('end', () => {
            writeFileSync('./text.txt', decodeURIComponent(Buffer.concat(list).toString()));
        })
        res.statusCode = 302;
        res.setHeader('Location', '/');
        return res.end();
    }
    res.statusCode = 200;
    res.write('<html><body>');
    res.write('hello world');
    res.write('</html></body>');
    res.end();
});
server.on('listening', () => {
    console.log('服务器启动了');
})
server.listen(443, '127.0.0.1')